<template>
  <van-nav-bar title="文件上传" />

 <div>
   <van-field v-model="formData.url" label="上传地址" placeholder="" />
   
   <van-field v-model="formData.filePath" label="本地文件" placeholder="点击选择" @click="startGetMedia"/>
   <div>
    <van-button type="primary" style=" margin-top: 20px;" @click="downloadFile" :loading="uploading">上传文件</van-button>
 </div>
  <div>{{result  }}</div>
 </div>
</template>

<script setup lang='ts' name='' >
// Your script here

import { ref } from "vue";

let formData = ref<any>({
  filePath:"",
  url:"http://101.207.130.194:58000/file/upload",
  header:{
    test1:'123123123',
    Authorization:'Bearer tGBdkJzSUFkT5p0mJZybv0Thrh1YpkgM5Sw8jHCmn5j53MjOKAn9b3LznORc8vUH'
  },
  formData:null,
  name:"file",
}) 
let result = ref("")
let uploading = ref(false);

const downloadFile= ()=> {

 //转码
 formData.value.url = encodeURIComponent( formData.value.url)

 uploading.value = true;
 (window as any).whJSBridge.uploadFile(JSON.stringify( formData.value)).then(
   function(res:any) {
     result.value = res
     uploading.value = false;
     alert('上传成功：' + JSON.stringify(res))
   }).catch(function(err:any) {
    uploading.value = false;
   if ('object' == typeof err) {
     alert('上传失败：' + JSON.stringify(err))
   } else {
     alert('上传失败：' + err)
   }
 });

}


const startGetMedia = () => {
  (window as any).whJSBridge.getMedia(getMediaCallback, JSON.stringify({
  mediaType: "file",
  count:1
})).then(
    function(res:any) {
      console.log("打开媒体成功");
    }).catch((err:any) => {
    console.log(err);
    alert(err);
  })
};


function getMediaCallback(dataStr:any) {
  const data = JSON.parse(dataStr);

  console.log("getMediaCallback");
  if (data.flag) {
    formData.value.filePath  = data.data;
  } else {
    //用户取消了，拍照或者选择图片
  }
}
</script>

<style scoped >
/* Your styles here */
</style>